<template>
  <div id="map"></div>
</template>

<script setup>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import XYZ from "ol/source/XYZ";
import Feature from "ol/Feature";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Point from "ol/geom/Point";
import LineString from "ol/geom/LineString";
import { fromLonLat } from "ol/proj";
import { Circle, Fill, Stroke, Style } from "ol/style";
import { onMounted } from "@vue/runtime-core";
import nansha_data from "./nansha_data";

let map;

// 创建地图容器
function initMap() {
  map = new Map({
    target: "map",
    // 天地图
    layers: [
      new TileLayer({
        source: new XYZ({
          url: "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
        }),
      }),
    ],
    // 南沙区中心点
    view: new View({
      center: fromLonLat([113.44, 22.73]),
      zoom: 10,
    }),
  });
}
// 绘制点要素
function addPoint() {
  const pointFeature = [];
  for (let i = 0; i <= nansha_data.junction_x.length - 1; i++) {
    pointFeature.push(
      new Feature({
        geometry: new Point(
          fromLonLat([nansha_data.junction_y[i], nansha_data.junction_x[i]])
        ),
        name: "Point",
      })
    );
  }

  // 创建矢量图层
  const vectorLayer = new VectorLayer({
    source: new VectorSource({
      features: pointFeature,
    }),
    style: new Style({
      image: new Circle({
        radius: 5,
        fill: new Fill({
          color: "rgba(255, 0, 0, 0.6)",
        }),
      }),
    }),
  });

  // 将矢量图层添加到地图上
  map.addLayer(vectorLayer);
}
// 绘制线要素
function addLine() {
  const lineFeature = [];
  for (let i = 0; i <= nansha_data.pipe_vertices.length - 1; i++) {
    let res = [];
    nansha_data.pipe_vertices[i].forEach((item) => {
      res.push(fromLonLat([item[1], item[0]]));
    });
    lineFeature.push(
      new Feature({
        geometry: new LineString(res),
        name: "Line",
      })
    );
  }

  // 创建矢量图层
  const vectorLayer = new VectorLayer({
    source: new VectorSource({
      features: lineFeature,
    }),
    style: new Style({
      stroke: new Stroke({
        color: "rgba(0, 0, 255, 0.6)",
        width: 10,
      }),
    }),
  });

  // 将矢量图层添加到地图上
  map.addLayer(vectorLayer);
}

onMounted(() => {
  initMap();
  addLine();
  addPoint();
});
</script>

<style scoped>
#map {
  width: 100vw;
  height: 100vh;
}
</style>
